package com.situ.blog.controller;

import com.situ.blog.util.JSONResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {

    //浏览器传递过来的图片信息都封装到MultipartFile file
    @RequestMapping("/uploadImage")
    @ResponseBody
    public JSONResult uploadImage(MultipartFile file) {
        System.out.println("UploadController.uploadImage");
        String filename = file.getOriginalFilename();
        System.out.println("filename: " + filename);//1.png
        //6b948083a13a4df2a0b06aa1bd29c236
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String extension = FilenameUtils.getExtension(filename);//png
        String newFilename = uuid + "." + extension;//6b948083a13a4df2a0b06aa1bd29c236.png

        String filePath = "D:\\mypic\\" + newFilename;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONResult.ok("上传成功", newFilename);
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);//ed37389d-824e-4726-a8b0-8082d97de997
        System.out.println(uuid.replace("-", ""));//6b948083a13a4df2a0b06aa1bd29c236
    }
}
